<template>
  <div class="user-health-container">

    <!-- 健康概览头部 -->
    <div class="health-header">
      <div class="header-content">
        <div class="title-section">
          <el-button
              type="primary"
              :icon="ArrowLeft"
              @click="handleBack"
              class="back-btn"
          >
            返回
          </el-button>
          <h2 class="title">健康数据趋势分析</h2>
          <p class="subtitle">查看您的健康指标变化趋势</p>
        </div>
        <div class="header-controls">
          <div class="date-control">
            <el-date-picker
                v-model="selectedMonth"
                type="month"
                value-format="YYYY-MM"
                placeholder="选择月份"
                @change="handleDateChange"
                class="month-picker"
            />
            <el-tooltip content="刷新数据" placement="top">
              <el-button
                  type="primary"
                  :icon="Refresh"
                  circle
                  @click="fetchHealthData"
                  class="refresh-btn"
              />
            </el-tooltip>
          </div>
          <div class="quick-select">
            <el-radio-group
                v-model="activePeriod"
                size="default"
                @change="handlePeriodChange"
            >
              <el-radio-button label="week">本周</el-radio-button>
              <el-radio-button label="month">本月</el-radio-button>
              <el-radio-button label="quarter">近三月</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要图表区域 -->
    <div class="main-charts">
      <div class="charts-row top-row">
        <!-- 血糖图表 -->
        <el-card class="chart-card glucose-chart">
          <div class="chart-header">
            <div class="chart-title">
              <el-icon class="icon"><Sugar /></el-icon>
              <h3>血糖趋势分析</h3>
            </div>
            <div class="current-status">
              <span class="label">最新测量值：</span>
              <el-tag
                  :type="glucoseStatus.type"
                  effect="plain"
                  class="status-tag"
              >
                {{ glucoseStatus.value }} mmol/L
              </el-tag>
              <span class="status-text">{{ glucoseStatus.text }}</span>
            </div>
          </div>
          <div
              ref="glucoseChart"
              class="chart-content"
              v-loading="isLoading"
          ></div>
        </el-card>

        <!-- 血压图表 -->
        <el-card class="chart-card pressure-chart">
          <div class="chart-header">
            <div class="chart-title">
              <el-icon class="icon"><Monitor /></el-icon>
              <h3>血压趋势分析</h3>
            </div>
            <div class="current-status">
              <span class="label">最新测量值：</span>
              <el-tag
                  :type="pressureStatus.type"
                  effect="plain"
                  class="status-tag"
              >
                {{ pressureStatus.value }} mmHg
              </el-tag>
              <span class="status-text">{{ pressureStatus.text }}</span>
            </div>
          </div>
          <div
              ref="pressureChart"
              class="chart-content"
              v-loading="isLoading"
          ></div>
        </el-card>
      </div>

      <div class="charts-row bottom-row">
        <!-- 热量图表 -->
        <el-card class="chart-card calories-chart">
          <div class="chart-header">
            <div class="chart-title">
              <el-icon class="icon"><Food /></el-icon>
              <h3>热量趋势分析</h3>
            </div>
            <div class="current-status">
              <div class="calories-detail">
                <span class="label">今日摄入：</span>
                <el-tag type="success" effect="plain" class="status-tag">
                  {{ caloriesStatus.intake }} kcal
                </el-tag>
              </div>
              <div class="calories-detail">
                <span class="label">今日消耗：</span>
                <el-tag type="warning" effect="plain" class="status-tag">
                  {{ caloriesStatus.burn }} kcal
                </el-tag>
              </div>
              <div class="calories-detail">
                <span class="label">净热量：</span>
                <el-tag
                    :type="caloriesStatus.type"
                    effect="plain"
                    class="status-tag"
                >
                  {{ caloriesStatus.value }} kcal
                </el-tag>
                <span class="status-text">{{ caloriesStatus.text }}</span>
              </div>
            </div>
          </div>
          <div
              ref="caloriesChart"
              class="chart-content"
              v-loading="isLoading"
          ></div>
        </el-card>
      </div>
    </div>

    <!-- 健康数据摘要 -->
    <div class="health-summary">
      <el-row :gutter="20">
        <!-- 血糖摘要 -->
        <el-col :xs="24" :sm="12" :md="8">
          <summary-card
              icon="Sugar"
              title="平均血糖"
              :value="stats.glucose.avg"
              unit="mmol/L"
              :trend="stats.glucose.trend"
              trend-label="周同比"
          />
        </el-col>

        <!-- 血压摘要 -->
        <el-col :xs="24" :sm="12" :md="8">
          <summary-card
              icon="Monitor"
              title="平均血压"
              :value="stats.pressure.avg"
              unit="mmHg"
              :trend="stats.pressure.trend"
              trend-label="周同比"
          />
        </el-col>

        <!-- 测量次数 -->
        <el-col :xs="24" :sm="12" :md="8">
          <summary-card
              icon="Clock"
              title="总测量次数"
              :value="stats.totalMeasurements"
              :show-trend="false"
          />
        </el-col>
      </el-row>
    </div>

    <!-- 空状态提示 -->
    <div v-if="!hasData" class="empty-state">
      <el-empty description="暂无相关健康数据">
        <template #extra>
          <el-button
              type="primary"
              @click="handleFirstMeasurement"
          >
            立即添加测量记录
          </el-button>
        </template>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import {
  getBloodSugarData,
  getBloodPressureData
} from '@/api/healthSys/records'
import { listDiet } from '@/api/healthSys/diet'
import { listSport } from '@/api/healthSys/sport'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import useUserStore from "@/store/modules/user.js";
import { ArrowLeft, Refresh } from '@element-plus/icons-vue'

// 用户状态管理
const router = useRouter()
const userStore = useUserStore()
const userId = computed(() => userStore.id)

// 图表实例
const glucoseChart = ref(null)
const pressureChart = ref(null)
const caloriesChart = ref(null)
let glucoseChartInstance = null
let pressureChartInstance = null
let caloriesChartInstance = null

// 响应式数据
const isLoading = ref(false)
const activePeriod = ref('month') // week/month/quarter
const selectedMonth = ref(dayjs().format('YYYY-MM'))
const rawGlucoseData = ref([])
const rawPressureData = ref([])
const rawCaloriesData = ref([])
const rawSportData = ref([])

// 图表基础配置
const chartBaseOptions = {
  grid: {
    top: 40,
    left: 40,
    right: 20,
    bottom: 30,
    containLabel: true
  },
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(255,255,255,0.98)',
    borderWidth: 0,
    textStyle: {
      color: '#333',
      fontSize: 12
    },
    extraCssText: 'box-shadow: 0 4px 12px rgba(0,0,0,0.15);'
  },
  xAxis: {
    type: 'category',
    axisLabel: {
      color: '#666',
      fontSize: 12
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      color: '#666',
      fontSize: 12
    }
  }
}

// 计算属性
const hasData = computed(() =>
    rawGlucoseData.value.length > 0 || rawPressureData.value.length > 0
)

const glucoseStatus = computed(() => {
  const lastRecord = rawGlucoseData.value[rawGlucoseData.value.length - 1]
  const value = lastRecord?.bloodSugar || 0
  return {
    value: value.toFixed(1),
    type: value < 3.9 ? 'success' : value < 7.8 ? 'warning' : 'danger',
    text: value < 3.9 ? '正常' : value < 7.8 ? '注意' : '异常'
  }
})

const pressureStatus = computed(() => {
  const lastRecord = rawPressureData.value[rawPressureData.value.length - 1]
  const systolic = lastRecord?.systolic || 0
  const diastolic = lastRecord?.diastolic || 0
  const type = systolic > 140 || diastolic > 90 ? 'danger'
      : systolic > 130 || diastolic > 85 ? 'warning' : 'success'
  return {
    value: `${systolic}/${diastolic}`,
    type,
    text: type === 'success' ? '正常' : type === 'warning' ? '偏高' : '异常'
  }
})

const caloriesStatus = computed(() => {
  const lastRecord = rawCaloriesData.value[rawCaloriesData.value.length - 1]
  const value = lastRecord?.calories || 0
  const intake = lastRecord?.intake || 0
  const burn = lastRecord?.burn || 0
  return {
    value: value.toFixed(0),
    intake: intake.toFixed(0),
    burn: burn.toFixed(0),
    type: value < 0 ? 'danger' : value < 500 ? 'success' : 'warning',
    text: value < 0 ? '热量赤字' : value < 500 ? '正常' : '热量盈余'
  }
})

const stats = computed(() => ({
  glucose: {
    avg: calculateAverage(rawGlucoseData.value, 'bloodSugar'),
    trend: calculateTrend(rawGlucoseData.value, 'bloodSugar')
  },
  pressure: {
    avg: calculateBloodPressureAvg(),
    trend: calculateBloodPressureTrend()
  },
  totalMeasurements: rawGlucoseData.value.length + rawPressureData.value.length
}))

// 生命周期钩子
onMounted(async () => {
  await initCharts()
  await fetchHealthData()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  glucoseChartInstance?.dispose()
  pressureChartInstance?.dispose()
  caloriesChartInstance?.dispose()
})

// 方法定义
const initCharts = async () => {
  if (!glucoseChart.value || !pressureChart.value || !caloriesChart.value) return

  glucoseChartInstance = echarts.init(glucoseChart.value)
  pressureChartInstance = echarts.init(pressureChart.value)
  caloriesChartInstance = echarts.init(caloriesChart.value)

  // 血糖图表配置
  glucoseChartInstance.setOption({
    ...chartBaseOptions,
    title: { text: '血糖趋势 (mmol/L)', left: 'center', top: 10, textStyle: { fontSize: 14 } },
    color: ['#36a3eb'],
    series: [{
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(54, 163, 235, 0.3)' },
          { offset: 1, color: 'rgba(54, 163, 235, 0.01)' }
        ])
      }
    }]
  })

  // 血压图表配置
  pressureChartInstance.setOption({
    ...chartBaseOptions,
    title: { text: '血压趋势 (mmHg)', left: 'center', top: 10, textStyle: { fontSize: 14 } },
    color: ['#ff7676', '#67c23a'],
    legend: {
      data: ['收缩压', '舒张压'],
      top: 35,
      textStyle: { fontSize: 12 },
      itemGap: 30,
      itemWidth: 10,
      itemHeight: 10
    },
    grid: {
      top: 70,
      left: 40,
      right: 20,
      bottom: 30,
      containLabel: true
    },
    series: [
      { name: '收缩压', type: 'line', smooth: true, symbol: 'circle', symbolSize: 6 },
      { name: '舒张压', type: 'line', smooth: true, symbol: 'circle', symbolSize: 6 }
    ]
  })

  // 热量图表配置
  caloriesChartInstance.setOption({
    ...chartBaseOptions,
    title: { text: '热量收支趋势 (kcal)', left: 'center', top: 10, textStyle: { fontSize: 14 } },
    color: ['#ff9f7f', '#67c23a', '#ff7676'],
    legend: {
      data: ['净热量', '摄入量', '消耗量'],
      top: 35,
      textStyle: { fontSize: 12 },
      itemGap: 30,
      itemWidth: 10,
      itemHeight: 10
    },
    grid: {
      top: 70,
      left: 40,
      right: 20,
      bottom: 30,
      containLabel: true
    },
    series: [
      {
        name: '净热量',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(255, 159, 127, 0.3)' },
            { offset: 1, color: 'rgba(255, 159, 127, 0.01)' }
          ])
        }
      },
      {
        name: '摄入量',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: { type: 'dashed' }
      },
      {
        name: '消耗量',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: { type: 'dashed' }
      }
    ]
  })
}

const fetchHealthData = async () => {
  try {
    isLoading.value = true;
    if (!userId.value) {
      ElMessage.error('用户未登录')
      return
    }
    
    const dateRange = getDateRangeParams();
    const params = {
      userId: userId.value,
      ...dateRange
    };
    
    const [glucoseRes, pressureRes, caloriesRes, sportRes] = await Promise.all([
      getBloodSugarData(params),
      getBloodPressureData(params),
      listDiet(params),
      listSport({
        userId: userId.value,
        beginDate: dateRange.startDate,
        endDate: dateRange.endDate
      })
    ])

    rawGlucoseData.value = processGlucoseData(glucoseRes.data)
    rawPressureData.value = processPressureData(pressureRes.data)
    rawSportData.value = sportRes.rows
    rawCaloriesData.value = processCaloriesData(caloriesRes.rows)
    
    nextTick(() => {
      updateCharts()
    })

  } catch (error) {
    ElMessage.error('数据加载失败: ' + error.message)
  } finally {
    isLoading.value = false
  }
}

const processGlucoseData = (data) => {
  return data.map(item => ({
    date: dayjs(item.recordTime).format('MM-DD'),
    bloodSugar: Number(item.bloodSugar)
  })).sort((a, b) => dayjs(a.date).unix() - dayjs(b.date).unix())
}

const processPressureData = (data) => {
  return data.map(item => ({
    date: dayjs(item.recordTime).format('MM-DD'),
    systolic: Number(item.systolic),
    diastolic: Number(item.diastolic)
  })).sort((a, b) => dayjs(a.date).unix() - dayjs(b.date).unix())
}

const processCaloriesData = (data) => {
  // 按日期分组并计算每日总热量
  const dailyCalories = data.reduce((acc, item) => {
    const date = dayjs(item.recordTime).format('MM-DD')
    if (!acc[date]) {
      acc[date] = {
        intake: 0,
        burn: 0
      }
    }
    acc[date].intake += Number(item.estimatedCalories)
    return acc
  }, {})

  // 添加运动消耗
  rawSportData.value.forEach(sport => {
    const date = dayjs(sport.recordDate).format('MM-DD')
    if (!dailyCalories[date]) {
      dailyCalories[date] = {
        intake: 0,
        burn: 0
      }
    }
    dailyCalories[date].burn += Number(sport.calories)
  })

  // 转换为数组格式并确保按日期排序
  return Object.entries(dailyCalories)
    .map(([date, data]) => ({
      date,
      calories: data.intake - data.burn,
      intake: data.intake,
      burn: data.burn
    }))
    .sort((a, b) => dayjs(a.date).unix() - dayjs(b.date).unix())
}

const updateCharts = () => {
  nextTick(() => {
    if (glucoseChartInstance) {
      glucoseChartInstance.setOption({
        xAxis: { data: rawGlucoseData.value.map(d => d.date) },
        series: [{ data: rawGlucoseData.value.map(d => d.bloodSugar) }]
      })
    }

    if (pressureChartInstance) {
      pressureChartInstance.setOption({
        xAxis: { data: rawPressureData.value.map(d => d.date) },
        series: [
          { data: rawPressureData.value.map(d => d.systolic) },
          { data: rawPressureData.value.map(d => d.diastolic) }
        ]
      })
    }

    if (caloriesChartInstance) {
      caloriesChartInstance.setOption({
        xAxis: { data: rawCaloriesData.value.map(d => d.date) },
        series: [
          { data: rawCaloriesData.value.map(d => d.calories) },
          { data: rawCaloriesData.value.map(d => d.intake) },
          { data: rawCaloriesData.value.map(d => d.burn) }
        ]
      })
    }
  })
}

const handleDateChange = () => {
  activePeriod.value = 'custom'
  fetchHealthData()
}

const handlePeriodChange = (period) => {
  selectedMonth.value = dayjs().format('YYYY-MM')
  fetchHealthData()
}

const getDateRangeParams = () => {
  const now = dayjs()
  const ranges = {
    week: [now.startOf('week'), now.endOf('week')],
    month: [now.startOf('month'), now.endOf('month')],
    quarter: [now.subtract(3, 'month'), now]
  }

  const [start, end] = activePeriod.value === 'custom'
      ? [dayjs(selectedMonth.value).startOf('month'), dayjs(selectedMonth.value).endOf('month')]
      : ranges[activePeriod.value]

  return {
    startDate: start.format('YYYY-MM-DD'),
    endDate: end.format('YYYY-MM-DD')
  }
}

const calculateAverage = (data, field) => {
  if (data.length === 0) return 0
  const sum = data.reduce((acc, cur) => acc + cur[field], 0)
  return parseFloat((sum / data.length).toFixed(1))
}

const calculateTrend = (data, field) => {
  if (data.length < 2) return 0
  const current = data.slice(-1)[0][field]
  const previous = data[0][field]
  return ((current - previous) / previous * 100).toFixed(1)
}

const calculateBloodPressureAvg = () => {
  if (rawPressureData.value.length === 0) return '0/0'
  const systolic = calculateAverage(rawPressureData.value, 'systolic')
  const diastolic = calculateAverage(rawPressureData.value, 'diastolic')
  return `${systolic.toFixed(0)}/${diastolic.toFixed(0)}`
}

const calculateBloodPressureTrend = () => {
  if (rawPressureData.value.length < 2) return 0
  const currentS = rawPressureData.value.slice(-1)[0].systolic
  const firstS = rawPressureData.value[0].systolic
  return ((currentS - firstS) / firstS * 100).toFixed(1)
}

const handleResize = () => {
  glucoseChartInstance?.resize()
  pressureChartInstance?.resize()
  caloriesChartInstance?.resize()
}

const handleFirstMeasurement = () => {
  // 跳转到新增记录页面
  router.push('/health/record/add')
}

// 添加返回方法
const handleBack = () => {
  router.go(-1)
}
</script>

<style lang="scss" scoped>
.user-health-container {
  max-width: 1440px;
  margin: 0 auto;
  padding: 24px;
  background-color: #f8f9fa;
  min-height: 100vh;

  // 头部区域
  .health-header {
    background: white;
    border-radius: 16px;
    padding: 32px;
    margin-bottom: 32px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 24px;

      .title-section {
        display: flex;
        align-items: center;
        gap: 24px;

        .back-btn {
          padding: 10px 20px;
          border-radius: 8px;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateX(-5px);
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
          }
        }

        .title {
          margin: 0;
          font-size: 28px;
          color: #1a1a1a;
          font-weight: 600;
          line-height: 1.2;
        }

        .subtitle {
          margin: 8px 0 0;
          font-size: 16px;
          color: #666;
        }
      }

      .header-controls {
        display: flex;
        gap: 24px;
        align-items: center;

        // 日期选择区域
        .date-control {
          display: flex;
          align-items: center;
          gap: 16px;

          :deep(.el-date-editor) {
            width: 200px;
            border-radius: 8px;
          }

          .refresh-btn {
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
            transition: all 0.3s ease;

            &:hover {
              transform: rotate(90deg);
            }
          }
        }

        // 快捷时间选择
        .quick-select {
          :deep(.el-radio-group) {
            display: flex;
            gap: 8px;
            padding: 4px;
            background: #f5f7fa;
            border-radius: 8px;

            .el-radio-button {
              --el-color-primary: #409EFF;

              &:not(.is-active) {
                .el-radio-button__inner {
                  border-color: transparent;
                  background: transparent;
                }
              }

              .el-radio-button__inner {
                border-radius: 6px;
                padding: 8px 16px;
                transition: all 0.3s ease;
              }
            }
          }
        }
      }
    }
  }

  // 主图表区域
  .main-charts {
    display: flex;
    flex-direction: column;
    gap: 24px;
    margin-bottom: 40px;

    .charts-row {
      display: grid;
      gap: 24px;

      &.top-row {
        grid-template-columns: repeat(2, 1fr);
      }

      &.bottom-row {
        grid-template-columns: 1fr;
      }
    }

    .chart-card {
      background: white;
      border-radius: 16px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      border-top-width: 4px;
      border-top-style: solid;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);

      &:hover {
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
        transform: translateY(-4px);
      }

      // 图表头部
      .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 20px;
        border-bottom: 1px solid #eee;

        .chart-title {
          display: flex;
          align-items: center;
          gap: 12px;

          .icon {
            font-size: 24px;
            padding: 8px;
            border-radius: 8px;
            background: rgba(64, 158, 255, 0.1);
            transition: all 0.3s ease;
          }

          h3 {
            margin: 0;
            font-size: 16px;
            color: #333;
            font-weight: 600;
          }
        }

        // 当前状态显示
        .current-status {
          display: flex;
          align-items: center;
          gap: 20px;

          .label {
            color: #666;
            font-size: 14px;
          }

          .status-tag {
            border-radius: 16px;
            padding: 4px 12px;
            border: none;
            font-size: 14px;
            transition: all 0.3s ease;

            &[type="success"] {
              background: #f6ffed;
              color: #52c41a;
            }
            &[type="warning"] {
              background: #fffbe6;
              color: #faad14;
            }
            &[type="danger"] {
              background: #fff2f0;
              color: #ff4d4f;
            }
          }

          .status-text {
            font-weight: 500;
            font-size: 14px;
          }
        }
      }

      // 图表内容区域
      .chart-content {
        height: 300px;
        padding: 16px 20px;
      }

      // 血糖图表特殊样式
      &.glucose-chart {
        border-color: #36a3eb;

        .icon {
          color: #36a3eb;
          background: rgba(54, 163, 235, 0.1);
        }
      }

      // 血压图表特殊样式
      &.pressure-chart {
        border-color: #ff7676;

        .icon {
          color: #ff7676;
          background: rgba(255, 118, 118, 0.1);
        }
      }

      // 热量图表特殊样式
      &.calories-chart {
        border-color: #ff9f7f;

        .icon {
          color: #ff9f7f;
          background: rgba(255, 159, 127, 0.1);
        }

        .current-status {
          display: flex;
          flex-direction: column;
          gap: 12px;

          .calories-detail {
            display: flex;
            align-items: center;
            gap: 12px;
          }
        }
      }
    }
  }

  // 健康摘要区域
  .health-summary {
    margin-top: 32px;
    background: white;
    border-radius: 16px;
    padding: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);

    :deep(.el-col) {
      margin-bottom: 0;
    }
  }

  // 空状态提示
  .empty-state {
    margin: 120px 0;
    text-align: center;
    padding: 48px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);

    :deep(.el-empty__description) {
      p {
        color: #666;
        margin: 24px 0;
        font-size: 16px;
      }
    }

    :deep(.el-button) {
      padding: 12px 32px;
      border-radius: 8px;
      font-size: 16px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
      }
    }
  }

  // 加载状态
  :deep(.el-loading-mask) {
    background-color: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(4px);

    .el-loading-spinner {
      .path {
        stroke: #409EFF;
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .user-health-container {
    padding: 20px;

    .main-charts {
      .charts-row {
        &.top-row {
          grid-template-columns: 1fr;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .user-health-container {
    padding: 16px;

    .health-header {
      padding: 24px;
      margin-bottom: 24px;

      .header-content {
        flex-direction: column;
        align-items: stretch;
        gap: 20px;

        .title-section {
          flex-direction: column;
          align-items: flex-start;
          gap: 16px;

          .back-btn {
            margin-bottom: 8px;
          }

          .title {
            font-size: 24px;
          }
        }

        .header-controls {
          flex-direction: column;
          gap: 16px;

          .date-control {
            justify-content: space-between;
          }
        }
      }
    }

    .main-charts {
      .chart-card {
        .chart-header {
          padding: 20px;
          flex-direction: column;
          align-items: flex-start;
          gap: 16px;

          .current-status {
            width: 100%;
            justify-content: space-between;
          }
        }

        .chart-content {
          height: 300px;
          padding: 20px;
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .user-health-container {
    .main-charts {
      .chart-card {
        .chart-header {
          .current-status {
            flex-direction: column;
            align-items: flex-start;
            gap: 12px;
          }
        }
      }
    }

    .empty-state {
      margin: 60px 0;
      padding: 32px;
    }
  }
}
</style>
